//
//  Tools.m
//  Teleport
//
//  Created by RLY on 2020/5/14.
//  Copyright © 2020 xxt. All rights reserved.
//

#import "Tools.h"

@implementation Tools

+ (NSInteger)timeInterval {
    return [[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] integerValue];
}

+ (NSString *)appVersion {
    NSDictionary *infoDictionary = [NSBundle.mainBundle infoDictionary];
    return infoDictionary[@"CFBundleShortVersionString"];
}

+ (NSString *)appName {
    NSDictionary *infoDictionary = [NSBundle.mainBundle infoDictionary];
    return infoDictionary[@"CFBundleName"];
}

+ (BOOL)checkNumberDecimal:(NSString *)str {
    return [[NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[0-9]+(\\.[0-9]{1,4})?$"] evaluateWithObject: str];
}

+ (BOOL)checkAmountDecimal:(NSString *)str {
    return [[NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[0-9]+(\\.[0-9]{1,2})?$"] evaluateWithObject: str];
}

+ (NSString *)videoLengthWithSeconds:(long)seconds {
    NSString *theLastTime = nil;
    long second = seconds;
    if (seconds < 60) {
        theLastTime = [NSString stringWithFormat:@"00:%02zd", second];
    } else if(seconds >= 60 && seconds < 3600){
        theLastTime = [NSString stringWithFormat:@"%02zd:%02zd", second/60, second%60];
    } else if(seconds >= 3600){
        theLastTime = [NSString stringWithFormat:@"%02zd:%02zd:%02zd", second/3600, second%3600/60, second%60];
    }
    return theLastTime;
}
//字典转json 字符串
+ (NSString *)convertToJsonString:(NSDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}
//json字符串转字典
+ (NSDictionary *)convertToDict:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (UINavigationController *)currentNavController {
    return [self currentViewController].navigationController;
}
 
+ (UIViewController *)currentViewController {
    return [self getCurrentViewControllerFrom:[UIApplication sharedApplication].delegate.window.rootViewController];
}

+ (UIViewController *)getCurrentViewControllerFrom:(UIViewController *)rootVC {
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        currentVC = [self getCurrentViewControllerFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        currentVC = [self getCurrentViewControllerFrom:[(UINavigationController *)rootVC topViewController]];
    } else {
        currentVC = rootVC;
    }
    return currentVC;
}

+ (BOOL)isBangsScreen {
    BOOL result = NO;
    if (@available(iOS 11.0, *)) {
        UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
        result = window.safeAreaInsets.bottom > 0;
    }
    return result;
}



/**生成二维码图片 */
+ (void)createQRWithString:(NSString*)text QRSize:(CGSize)size finishBlock:(void (^)(UIImage *))finishBlock {
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //生成
        NSData *stringData = [text dataUsingEncoding: NSUTF8StringEncoding];
        CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
        [qrFilter setValue:stringData forKey:@"inputMessage"];
        [qrFilter setValue:@"H" forKey:@"inputCorrectionLevel"];
        CIImage *qrImage = qrFilter.outputImage;
        
        //绘制
        CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:qrImage fromRect:qrImage.extent];
        UIGraphicsBeginImageContext(size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetInterpolationQuality(context, kCGInterpolationNone);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
        UIImage *codeImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        CGImageRelease(cgImage);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (finishBlock) finishBlock(codeImage);
        });
    });
}

+ (UIImage *)avatarImage {
    return [UIImage imageWithContentsOfFile:USERICONPATH] ?: [UIImage imageNamed:defaultAvatarImageName];
}

+ (void)saveAvatarImageWithUrl:(NSString *)url complete:(void (^ _Nullable )(UIImage *))complete {
    [SDWebImageManager.sharedManager loadImageWithURL:[NSURL URLWithString:url] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if (!error) {
            [image asynImageSize:HeadPortraitSize color:[UIColor whiteColor] finishiBlock:^(UIImage *newImage) {
                [UIImagePNGRepresentation(image) writeToFile:USERICONPATH atomically:YES];
                if (complete) complete(newImage);
            }];
        }
    }];
}

+ (void)saveAvatarImageWithImage:(UIImage *)image {
    [UIImagePNGRepresentation(image) writeToFile:USERICONPATH atomically:YES];
}

+ (void)removeAvatarImage {
    [self removeFileAtPath:USERICONPATH];
 }

+ (BOOL)removeFileAtPath:(NSString *)path {
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    if ([defaultManager isDeletableFileAtPath:path]) {
        return [defaultManager removeItemAtPath:path error:nil];
    }
   return NO;
}

+ (NSString *)chineseChangePinyin:(NSString *)string {
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSString *pinYin = [str capitalizedString];
    return [pinYin substringToIndex:1];
}

+ (void)saveImageToPhotos:(UIImage *)image {
    if (!image) return;
    Tools *toos = [[Tools alloc] init];
    UIImageWriteToSavedPhotosAlbum(image, toos, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if(error) {
        [TJHud showAutoHideMessage:@"保存图片失败"];
    } else {
        [TJHud showAutoHideMessage:@"保存图片成功"];
    }
}
 // 生成一张图片
 +(UIImage *)snapshotSingleView:(UIView *)view

 {
     UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
     
     [view.layer renderInContext:UIGraphicsGetCurrentContext()];
     
     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
     
     UIGraphicsEndImageContext();
     return image;
     
 }
#pragma mark   -----浮点数精度处理-----
+ (NSString *)reviseString:(NSString *)value {
    NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithDouble:value.doubleValue roundingScale:6];
     return [NSString stringFromNumber:decimalNumber fractionDigits:6];
}

+ (NSString *)CNYString:(NSString *)value {
    NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithDouble:value.doubleValue roundingScale:2];
     return [NSString stringFromNumber:decimalNumber fractionDigits:2];
}

+ (void)copyStringToPasteboard:(NSString *)string {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = string ?: @"";
    [TJHud showAutoHideMessage:@"复制成功".localizedString];
}

+ (NSString *)hiddenPhoneMiddleWithString:(NSString *)string {
    if (string.length == 11) {
        return [string stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    return @"";
}

 
@end
